<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { connectSuperAgentSSE } from '../services/api'

interface Message {
  id: number
  content: string
  isUser: boolean
  timestamp: Date
  step?: number // 添加步骤标识
}

const router = useRouter()
const message = ref('')
const messages = ref<Message[]>([])
const currentStep = ref(1)
const eventSource = ref<EventSource | null>(null)
const isLoading = ref(false)
const isAIResponding = ref(false) // 新增：AI是否正在回答

// 返回主页
const goBack = () => {
  router.push('/')
}

// 发送消息
const sendMessage = () => {
  if (!message.value.trim() || isAIResponding.value) return
  
  // 添加用户消息到列表
  messages.value.push({
    id: Date.now(),
    content: message.value,
    isUser: true,
    timestamp: new Date()
  })
  
  // 显示加载状态
  isLoading.value = true
  isAIResponding.value = true // 设置AI正在回答状态
  
  // 关闭之前的连接
  if (eventSource.value) {
    eventSource.value.close()
  }
  
  // 创建新的SSE连接
  const userMessage = message.value
  message.value = ''
  
  // 连接SSE
  eventSource.value = connectSuperAgentSSE(userMessage)
  
  // 创建AI回复的消息对象
  const aiMessageId = Date.now() + 1
  let aiResponse = ''
  
  messages.value.push({
    id: aiMessageId,
    content: '',
    isUser: false,
    timestamp: new Date(),
    step: currentStep.value
  })
  
  // 滚动到底部
  scrollToBottom()
  
  // 监听SSE事件
  eventSource.value.onmessage = (event) => {
    const data = event.data
    
    if (data !== '[DONE]') {
      aiResponse += data
      
      // 更新AI消息内容
      const aiMessageIndex = messages.value.findIndex(msg => msg.id === aiMessageId)
      if (aiMessageIndex !== -1) {
        messages.value[aiMessageIndex].content = aiResponse
      }
      
      // 每次收到新消息都滚动到底部
      scrollToBottom()
    } else {
      // 流结束，关闭连接
      if (eventSource.value) {
        eventSource.value.close()
        eventSource.value = null
      }
      
      // 增加步骤计数
      currentStep.value++
      isAIResponding.value = false // 重置AI回答状态
      isLoading.value = false // 在流结束时才设置加载状态为false
    }
  }
  
  eventSource.value.onerror = () => {
    isLoading.value = false
    isAIResponding.value = false // 发生错误时也重置状态
    if (eventSource.value) {
      eventSource.value.close()
      eventSource.value = null
    }
  }
}

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    const chatContainer = document.querySelector('.chat-messages')
    if (chatContainer) {
      chatContainer.scrollTop = chatContainer.scrollHeight
    }
  }, 50)
}

// 监听消息变化，自动滚动
const watchMessages = () => {
  scrollToBottom()
}

// 监听消息数组变化，自动滚动
watch(messages, () => {
  scrollToBottom()
}, { deep: true })

// 组件挂载时
onMounted(() => {
  // 添加欢迎消息
  messages.value.push({
    id: Date.now(),
    content: '你好！我是AI超级智能体，我可以帮助你解决各种问题。请告诉我你需要什么帮助？',
    isUser: false,
    timestamp: new Date(),
    step: 0
  })
  
  // 初始滚动到底部
  scrollToBottom()
})

// 组件卸载时关闭SSE连接
onUnmounted(() => {
  if (eventSource.value) {
    eventSource.value.close()
    eventSource.value = null
  }
})
</script>

<template>
  <div class="chat-container">
    <div class="chat-header">
      <button class="back-button" @click="goBack">返回</button>
      <h1>AI 超级智能体</h1>
    </div>
    
    <div class="chat-messages" @updated="watchMessages">
      <div 
        v-for="msg in messages" 
        :key="msg.id" 
        :class="['message', msg.isUser ? 'user-message' : 'ai-message']">
        <div class="avatar" :class="{ 'user-avatar': msg.isUser, 'ai-avatar': !msg.isUser }">
          <div class="avatar-image">
            {{ msg.isUser ? '👤' : '🤖' }}
          </div>
        </div>
        <div class="message-content">
          <div v-if="msg.step && !msg.isUser" class="step-indicator">步骤 {{ msg.step }}</div>
          <div class="message-text">{{ msg.content }}</div>
          <div class="message-time">
            {{ msg.timestamp.toLocaleTimeString() }}
          </div>
        </div>
      </div>
      
      <div v-if="isLoading" class="typing-indicator">
        <div class="dot"></div>
        <div class="dot"></div>
        <div class="dot"></div>
      </div>
    </div>
    
    <div class="chat-input">
      <input 
        v-model="message" 
        @keyup.enter="!isAIResponding && sendMessage()" 
        placeholder="输入消息..." 
        :disabled="isLoading"
      />
      <button @click="sendMessage" :disabled="isLoading || !message.trim() || isAIResponding">
        发送
      </button>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 800px;
  margin: 0 auto;
  background-color: var(--background-dark);
  position: relative;
}

.chat-header {
  display: flex;
  align-items: center;
  padding: 1rem;
  background-color: var(--secondary-color);
  position: relative;
  border-bottom: 1px solid rgba(66, 184, 131, 0.2);
}

.back-button {
  background: none;
  border: none;
  color: var(--primary-color);
  cursor: pointer;
  font-size: 1rem;
  padding: 0.5rem;
}

.chat-header h1 {
  flex: 1;
  text-align: center;
  margin: 0;
  font-size: 1.5rem;
  color: var(--primary-color);
}

.chat-messages {
  flex: 1;
  padding: 1rem;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  background-image: 
    radial-gradient(circle at 25% 25%, rgba(66, 184, 131, 0.03) 0%, transparent 50%),
    radial-gradient(circle at 75% 75%, rgba(66, 184, 131, 0.03) 0%, transparent 50%);
}

.message {
  display: flex;
  margin-bottom: 1rem;
  align-items: flex-start;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 0.5rem;
  flex-shrink: 0;
}

.avatar-image {
  font-size: 1.5rem;
}

.user-avatar {
  background-color: rgba(66, 184, 131, 0.2);
  order: 2;
}

.ai-avatar {
  background-color: rgba(44, 62, 80, 0.3);
}

.message-content {
  max-width: calc(70% - 50px);
  padding: 0.8rem 1rem;
  border-radius: 1rem;
  position: relative;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.user-message .message-content {
  background-color: var(--primary-color);
  color: white;
  border-bottom-right-radius: 0.2rem;
}

.ai-message .message-content {
  background-color: var(--secondary-color);
  color: white;
  border-bottom-left-radius: 0.2rem;
}

.step-indicator {
  font-size: 0.7rem;
  color: var(--primary-color);
  margin-bottom: 0.3rem;
  font-weight: bold;
}

.message-text {
  word-break: break-word;
  white-space: pre-wrap;
  text-align: left;
}

.message-time {
  font-size: 0.7rem;
  opacity: 0.7;
  margin-top: 0.3rem;
  text-align: right;
}

.typing-indicator {
  display: flex;
  padding: 0.8rem 1rem;
  background-color: var(--secondary-color);
  border-radius: 1rem;
  width: fit-content;
  align-self: flex-start;
  margin-bottom: 1rem;
  margin-left: 50px;
}

.dot {
  width: 8px;
  height: 8px;
  background-color: #b8c2cc;
  border-radius: 50%;
  margin: 0 2px;
  animation: bounce 1.4s infinite ease-in-out;
}

.dot:nth-child(1) { animation-delay: 0s; }
.dot:nth-child(2) { animation-delay: 0.2s; }
.dot:nth-child(3) { animation-delay: 0.4s; }

@keyframes bounce {
  0%, 80%, 100% { transform: translateY(0); }
  40% { transform: translateY(-8px); }
}

.chat-input {
  display: flex;
  padding: 1rem;
  background-color: var(--secondary-color);
  gap: 0.5rem;
  border-top: 1px solid rgba(66, 184, 131, 0.2);
}

.chat-input input {
  flex: 1;
  padding: 0.8rem 1rem;
  border: none;
  border-radius: 2rem;
  background-color: var(--background-dark);
  color: var(--text-light);
  outline: none;
  transition: box-shadow var(--transition-speed);
}

.chat-input input:focus {
  box-shadow: 0 0 0 2px rgba(66, 184, 131, 0.3);
}

.chat-input button {
  padding: 0.8rem 1.5rem;
  border: none;
  border-radius: 2rem;
  background-color: var(--primary-color);
  color: white;
  cursor: pointer;
  transition: background-color var(--transition-speed);
}

.chat-input button:hover:not(:disabled) {
  background-color: var(--primary-dark);
}

.chat-input button:disabled {
  background-color: var(--secondary-color);
  cursor: not-allowed;
  opacity: 0.7;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    max-width: 100%;
  }
  
  .message-content {
    max-width: calc(80% - 40px);
  }
}

@media (max-width: 480px) {
  .avatar {
    width: 32px;
    height: 32px;
  }
  
  .avatar-image {
    font-size: 1.2rem;
  }
  
  .message-content {
    max-width: calc(85% - 32px);
    padding: 0.6rem 0.8rem;
  }
  
  .chat-input {
    padding: 0.8rem;
  }
  
  .chat-input input {
    padding: 0.6rem 0.8rem;
  }
  
  .chat-input button {
    padding: 0.6rem 1rem;
  }
}
</style>